<?php

namespace app\api\controller;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Api;
use app\common\library\Mqtt;
use app\admin\model\Device;
use app\admin\model\WeighRecord;
class Hardwaresms extends Api
{
 	
    protected $noNeedLogin = ['receive','editdevice','threshold','start','refresh','warm','unload','test'];

    public function _initialize()
    {
        parent::_initialize();
        $this->device = model('\addons\manystore\model\Device');
    }

    //达到阈值操作
    public function threshold()
    {   
        $device_id = $this->request->post('device_id',0,'intval');
        if(!$device_id) $this->error('参数错误');

        $result = $this->device->thresholdAfter($device_id, $this->request->post());
        if($result !== true) $this->error($result);

        $this->success(__('Success'));
    }

    //接收设备状态
    public function editdevice()
    {
        $device_id = $this->request->post('id',0,'intval');
        $status = $this->request->post('status',0,'intval');
        $result = \addons\manystore\model\Device::editStatus($device_id, $status);
        if($result !== true) $this->error($result);
        $this->success(__('Success'));
    }

    /**
     * 硬件上报的设备消息
     */
    public function receive(){
        $content = file_get_contents('php://input');
        //file_put_contents('devlog.txt',date("Y-m-d H:i:s")."--receive--".$content."\r\n",FILE_APPEND);
        $res=json_decode($content,true);
        if(!isset($res['topic'])){
             return;
        }
        logs(['title'=>'硬件上报信息','logs'=>$content,'type'=>'mqtt']);
        $uuid=str_replace('wuwo_weight/data/','',$res['topic']);
        if(!$uuid || empty($uuid)){
        		exit;
        }else{
 			 if(empty($res['msg'])) exit;
 			 $msg = json_decode($res['msg'],true);
 			 $type = $msg['head'] ?? '';
 			 switch ($type) {
                case 'online': //设备上线
                    $find = Device::where("imei",$msg['imei'])->find();
                    if(!$find){
                          logs(['title'=>'新增设备信息','logs'=>$content,'type'=>'mqtt']);
                          $aid = Device::create(['imei'=>$msg['imei'] ?? '','iccid'=>$msg['iccid']??'','boot_version'=>$msg['version'] ?? '','status'=>1,'rssi'=>31]);
                    }
                    break;
 			 	case 'data_pack':  //称重上报
 			 		$weight_all = $msg['datas'][0]['weight_all'] ?? 0;
 			 		$weight_curr =  $msg['datas'][0]['weight_curr'] ?? 0;
 			 		$data_num = $msg['datas'][0]['data_num'] ?? 1;
 			 		if($weight_all){
 			 			  $device = Device::where("imei",$uuid)->find();
                          if(intval($device['merchant_id']) == '' || $device['is_bang'] == 0){
                              return;
                          }
 			 			  $aid = WeighRecord::create(['weigh'=>$weight_all,'market_id'=>$device->market_id,'device_id'=>$device->id,'merchant_id'=>$device->merchant_id]);
                          if($aid){
                             logs(['title'=>'称重信息写入成功','logs'=>$content,'type'=>'mqtt']);
                          }
 			 			  
 			 		}
 			 		break;
 			 	case 're_calib': //完成校验
                    logs(['title'=>'校验接口进入','logs'=>$content,'type'=>'mqtt']);
                    if(isset($msg['result']) && $msg['result'] == 1){
                           $device = Device::where("imei",$uuid)->find();
                            Device::update([
                                'is_check'=>1,
                                'check_time'=>time()
                            ],['imei'=>$uuid]);  //校验完成
                            logs(['title'=>'校验完成','logs'=>$content,'type'=>'mqtt']);

                    }
                    break;
 			 	default:
 			 		// code...
 			 		break;
 			 }
 			  
 			 $this->success(__('Success'));
 			 return;

        }
    }

    private function toReceive($msg,$uuid,$extend=[]) {
        $this->receiveMsg($msg,$uuid);
    }

    private function receiveMsg($msg,$uuid,$extend=[]){
        $msg_decode = json_decode($msg,true);
        $data_type = $msg_decode['type'] ?? '';
        if($data_type == 'zaixian') $this->device->where('aaid', $uuid)->update(['status' => 1]);
        /*$cmd = $msg_decode['cmd'];
        $cmdlist = $this->hardware->getCmd();
        switch (strtoupper($cmd)) {
                //读取设备每个端口的状态
            case $cmdlist['swarm']:
            case $cmdlist['swarm2']:
                $this->device->readSwarmAfter($msg_decode,$uuid);
                break;
            default:
                break;
        }*/
    }

    /**
     * 开关机消息
     */
    public function start(){
        $content = file_get_contents('php://input');
        $res=json_decode($content,true);
   		
        124.58
        // if(!$res) $this->error('操作失败');
        if($res['event']=='client.connected'){             //开机
            logs(['title'=>'开机成功','logs'=>$content,'type'=>'mqtt']);
            $device = Device::where(['imei'=>$res['clientid']])->find();
            if($device) {
                $device->save(['status'=>1]);
            }
        }
        if($res['event']=='client.disconnected'){             //关机
            logs(['title'=>'关机成功','logs'=>$content,'type'=>'mqtt']);
            Device::update([
                    'status'=>0,
                    'end_off_time'=>time()
            ],['imei'=>$res['clientid']]);          
        }
    }

    //设备刷新
    public function refresh()
    {
        $code = $this->request->post('code','','trim');
        if(!$code) $this->error(__('Params Error'));

        $device = $this->device->where('code',$code)->find();
        if(!$device) $this->error('设备不存在');

        $result = $this->hardware->noserialPort($device['imei'],'refresh');
        $this->success(__('Success'));
    }

    public function warm()
    {   
        $device_id = $this->request->post('device_id', 0, 'intval');
        $post_data = $this->request->post()['data'] ?? [];
        
        if($post_data) {
            $result = $this->device->warm($device_id, $post_data);
            //if($result !== true) $this->error($result);
        }else{
            //$this->error('没有任何改变');
        }

        $this->success(__('Success'));
    }

    private function getClient($clientid)
    {
        if (strpos($clientid, '_') !== false) {
            return ['aaid', explode('_', $clientid)[1]];
        }else{
            return ['uuid', $clientid];
        }
    }

    public function test()
    {
        $res = (new \addons\manystore\model\WarmSms)->add('smoke', 32, '18856023309', 'tt');
        $this->success(__('Success'));
    }


}